<?php
namespace app\api\controller;

use think\Db;
use think\Exception;

class Thirdparty extends BaseController
{
    /**
     * 查询月租车信息
     */
    public function monthlyParking()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $vehicle_no = input('vehicle_no/s', '');
        
        if (!$vehicle_no) {
            return $this->renderError('请输入车牌号');
        }
        
        try {
            // 获取第三方API配置
            $api_config = Db::name('third_party_api')->where('name', '查询月租车')->find();
            if (!$api_config || !$api_config['status']) {
                return $this->renderError('服务暂不可用');
            }
            
            // 模拟调用第三方API
            $api_data = [
                'vehicle_no' => $vehicle_no,
                'member_id' => $member_id
            ];
            
            // 这里应该调用真实的第三方API
            // $response = $this->callThirdPartyApi($api_config['api_url'], $api_data, $api_config);
            
            // 模拟返回数据
            $mock_data = [
                'vehicle_no' => $vehicle_no,
                'is_monthly' => true,
                'start_date' => '2024-01-01',
                'end_date' => '2024-12-31',
                'parking_lot' => '大头停车场A区',
                'remaining_days' => 180,
                'status' => 'active'
            ];
            
            // 记录API调用日志
            $this->logApiCall('查询月租车', $api_data, $mock_data);
            
            return $this->renderSuccess($mock_data);
        } catch (Exception $e) {
            return $this->renderError('查询失败：' . $e->getMessage());
        }
    }
    
    /**
     * 车辆出场支付
     */
    public function exitPayment()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $vehicle_no = input('vehicle_no/s', '');
        $amount = input('amount/f', 0);
        $parking_duration = input('parking_duration/d', 0); // 停车时长（分钟）
        
        if (!$vehicle_no || !$amount) {
            return $this->renderError('参数错误');
        }
        
        try {
            // 获取第三方API配置
            $api_config = Db::name('third_party_api')->where('name', '出场支付')->find();
            if (!$api_config || !$api_config['status']) {
                return $this->renderError('支付服务暂不可用');
            }
            
            // 检查用户余额
            $member = Db::name('members')->where('member_id', $member_id)->find();
            if ($member['balance'] < $amount) {
                return $this->renderError('余额不足');
            }
            
            // 调用第三方支付API
            $api_data = [
                'vehicle_no' => $vehicle_no,
                'amount' => $amount,
                'member_id' => $member_id,
                'parking_duration' => $parking_duration
            ];
            
            // 模拟第三方API调用成功
            $payment_result = [
                'success' => true,
                'transaction_id' => 'TXN' . date('YmdHis') . rand(1000, 9999),
                'amount' => $amount,
                'vehicle_no' => $vehicle_no,
                'payment_time' => date('Y-m-d H:i:s')
            ];
            
            if ($payment_result['success']) {
                // 扣除用户余额
                Db::startTrans();
                try {
                    Db::name('members')->where('member_id', $member_id)->setDec('balance', $amount);
                    
                    // 记录余额变动
                    Db::name('balance_log')->insert([
                        'member_id' => $member_id,
                        'amount' => -$amount,
                        'remark' => "出场支付-{$vehicle_no}",
                        'created_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    // 记录API调用日志
                    $this->logApiCall('出场支付', $api_data, $payment_result);
                    
                    Db::commit();
                    return $this->renderSuccess($payment_result);
                } catch (Exception $e) {
                    Db::rollback();
                    throw $e;
                }
            } else {
                return $this->renderError('支付失败');
            }
        } catch (Exception $e) {
            return $this->renderError('支付失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取车辆信息
     */
    public function vehicleInfo()
    {
        $this->checkToken();
        
        $vehicle_no = input('vehicle_no/s', '');
        
        if (!$vehicle_no) {
            return $this->renderError('请输入车牌号');
        }
        
        try {
            // 获取第三方API配置
            $api_config = Db::name('third_party_api')->where('name', '获取车辆信息')->find();
            if (!$api_config || !$api_config['status']) {
                return $this->renderError('服务暂不可用');
            }
            
            // 模拟调用第三方API
            $api_data = ['vehicle_no' => $vehicle_no];
            
            // 模拟返回车辆信息
            $vehicle_info = [
                'vehicle_no' => $vehicle_no,
                'vehicle_type' => '小型汽车',
                'brand' => '丰田',
                'model' => '凯美瑞',
                'color' => '白色',
                'owner_name' => '张***',
                'is_registered' => true,
                'entry_time' => date('Y-m-d H:i:s', strtotime('-2 hours')),
                'parking_location' => 'A区-A001',
                'current_fee' => 10.00
            ];
            
            // 记录API调用日志
            $this->logApiCall('获取车辆信息', $api_data, $vehicle_info);
            
            return $this->renderSuccess($vehicle_info);
        } catch (Exception $e) {
            return $this->renderError('查询失败：' . $e->getMessage());
        }
    }
    
    /**
     * 商家减免
     */
    public function merchantDiscount()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $vehicle_no = input('vehicle_no/s', '');
        $merchant_code = input('merchant_code/s', '');
        $discount_amount = input('discount_amount/f', 0);
        
        if (!$vehicle_no || !$merchant_code || !$discount_amount) {
            return $this->renderError('参数错误');
        }
        
        try {
            // 获取第三方API配置
            $api_config = Db::name('third_party_api')->where('name', '商家减免')->find();
            if (!$api_config || !$api_config['status']) {
                return $this->renderError('服务暂不可用');
            }
            
            // 验证商家代码
            $merchant_info = [
                'MERCHANT001' => ['name' => '星巴克咖啡', 'discount_limit' => 20.00],
                'MERCHANT002' => ['name' => '麦当劳', 'discount_limit' => 15.00],
                'MERCHANT003' => ['name' => '肯德基', 'discount_limit' => 15.00]
            ];
            
            if (!isset($merchant_info[$merchant_code])) {
                return $this->renderError('商家代码无效');
            }
            
            $merchant = $merchant_info[$merchant_code];
            if ($discount_amount > $merchant['discount_limit']) {
                return $this->renderError('减免金额超过限制');
            }
            
            // 模拟调用第三方API
            $api_data = [
                'vehicle_no' => $vehicle_no,
                'merchant_code' => $merchant_code,
                'discount_amount' => $discount_amount,
                'member_id' => $member_id
            ];
            
            $discount_result = [
                'success' => true,
                'vehicle_no' => $vehicle_no,
                'merchant_name' => $merchant['name'],
                'discount_amount' => $discount_amount,
                'discount_time' => date('Y-m-d H:i:s'),
                'discount_id' => 'DIS' . date('YmdHis') . rand(1000, 9999)
            ];
            
            // 记录API调用日志
            $this->logApiCall('商家减免', $api_data, $discount_result);
            
            return $this->renderSuccess($discount_result);
        } catch (Exception $e) {
            return $this->renderError('减免失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取车辆订单记录
     */
    public function vehicleOrders()
    {
        $this->checkToken();
        
        $member_id = $this->getUserId();
        $vehicle_no = input('vehicle_no/s', '');
        $start_date = input('start_date/s', date('Y-m-d', strtotime('-30 days')));
        $end_date = input('end_date/s', date('Y-m-d'));
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        if (!$vehicle_no) {
            return $this->renderError('请输入车牌号');
        }
        
        try {
            // 获取第三方API配置
            $api_config = Db::name('third_party_api')->where('name', '获取车辆订单记录')->find();
            if (!$api_config || !$api_config['status']) {
                return $this->renderError('服务暂不可用');
            }
            
            // 模拟调用第三方API
            $api_data = [
                'vehicle_no' => $vehicle_no,
                'start_date' => $start_date,
                'end_date' => $end_date,
                'page' => $page,
                'limit' => $limit
            ];
            
            // 模拟返回订单记录
            $orders = [];
            for ($i = 1; $i <= $limit; $i++) {
                $orders[] = [
                    'order_id' => 'ORD' . date('Ymd') . sprintf('%04d', $i),
                    'vehicle_no' => $vehicle_no,
                    'entry_time' => date('Y-m-d H:i:s', strtotime("-{$i} days -2 hours")),
                    'exit_time' => date('Y-m-d H:i:s', strtotime("-{$i} days")),
                    'parking_duration' => 120, // 分钟
                    'amount' => rand(5, 25),
                    'discount_amount' => rand(0, 5),
                    'final_amount' => rand(5, 20),
                    'payment_method' => rand(0, 1) ? '余额支付' : '微信支付',
                    'status' => 'paid'
                ];
            }
            
            $result = [
                'data' => $orders,
                'total' => 100,
                'page' => $page,
                'limit' => $limit,
                'pages' => 10
            ];
            
            // 记录API调用日志
            $this->logApiCall('获取车辆订单记录', $api_data, $result);
            
            return $this->renderSuccess($result);
        } catch (Exception $e) {
            return $this->renderError('查询失败：' . $e->getMessage());
        }
    }
    
    /**
     * 记录API调用日志
     */
    private function logApiCall($api_name, $request_data, $response_data)
    {
        try {
            Db::name('third_party_api_logs')->insert([
                'api_name' => $api_name,
                'request_data' => json_encode($request_data),
                'response_data' => json_encode($response_data),
                'member_id' => $this->getUserId() ?? 0,
                'ip_address' => request()->ip(),
                'user_agent' => request()->header('user-agent'),
                'created_at' => date('Y-m-d H:i:s')
            ]);
        } catch (Exception $e) {
            // 日志记录失败不影响主流程
        }
    }
    
    /**
     * 调用第三方API（通用方法）
     */
    private function callThirdPartyApi($url, $data, $config = [])
    {
        $timeout = isset($config['config']) ? json_decode($config['config'], true)['timeout'] ?? 30 : 30;
        
        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . ($config['api_key'] ?? ''),
            ],
        ]);
        
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        
        if ($httpCode !== 200) {
            throw new Exception('API调用失败，HTTP状态码：' . $httpCode);
        }
        
        return json_decode($response, true);
    }
}